import wxApis from './wxApis';
import { request, isEffective, propsNotEmpty } from './utils';
/**
 * 重新登录
 * @param {*} options 
 * @param {*} wxappUserData 
 */
async function userLogin(options) {
  console.log('==userlogin==')
  const { code: userCode, errMsg } = await wxApis.login();
  if (!userCode) {
    throw new Error(errMsg);
  }
  propsNotEmpty(options, ['API_BASE_URL', 'APP_KEY']);

  const {
    APP_KEY,
    API_BASE_URL,
    LOGIN_API,
    HEADERS_CONFIG: headersConfig,
    ...rest
  } = options;
  console.log('==登录中，自定义接口：', LOGIN_API)
  return request(`${API_BASE_URL}${LOGIN_API || 'wechatMiniApp/miniprogram'}`, {
    code: userCode,
    appKey: APP_KEY,
    ...rest
  }, 'GET', headersConfig);
}

/**
 * 根据情况判断是否登录
 * @param  {Boolean} force 是否强制登录
 * @return {Promise}
 */
export default async function login(options = {}, wxappUser) {
  const { force = false, effectiveTimes = 2 * 60, ...rest } = options;
  try {
    if (force) {
      throw new Error('强制登录');
    }

    await wxApis.checkSession();

    if (wxappUser.token && isEffective(wxappUser.loginAt, effectiveTimes)) {
      return wxappUser;
    }

    throw new Error('缓存无效');
  } catch(error) {
    console.log('==重新登录原因：', error)
    // 强制登录 / 缓存无效 = 重新登录
    return userLogin(rest)
  }
}
